package com.lancoo.klgcourseware.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;

import com.alibaba.fastjson.JSON;
import com.lancoo.klgcourseware.R;
import com.lancoo.klgcourseware.base.BaseKlgActivity;
import com.lancoo.klgcourseware.entity.ExpressPracticeModel;
import com.lancoo.klgcourseware.entity.MoreSlideMenuModel;
import com.lancoo.klgcourseware.entity.WordArticulation;
import com.lancoo.klgcourseware.entity.bean.KlgCommonBean;
import com.lancoo.klgcourseware.listener.OnItemClickListener;
import com.lancoo.klgcourseware.manager.KlgCardDialogManager;
import com.lancoo.klgcourseware.ui.adapter.MoreMenuAdapter;
import com.lancoo.klgcourseware.ui.fragment.basicTrain.BasicTrainBaseFragment;
import com.lancoo.klgcourseware.ui.fragment.basicTrain.FillSpellTrainFragment;
import com.lancoo.klgcourseware.ui.fragment.basicTrain.PronunciatioPhraseTrainFragment;
import com.lancoo.klgcourseware.ui.fragment.basicTrain.PronunciatioTrainFragment;
import com.lancoo.klgcourseware.ui.fragment.basicTrain.SpellMemoryWriteFragment;
import com.lancoo.klgcourseware.ui.fragment.basicTrain.SpellTrainFragment;
import com.lancoo.klgcourseware.ui.fragment.basicTrain.UsageTrainFragment;
import com.lancoo.klgcourseware.ui.fragment.more.MoreRepeatFragment;
import com.lancoo.klgcourseware.ui.fragment.more.MoreTranslationFragment;
import com.lancoo.klgcourseware.utils.klog.KLog;

import java.util.ArrayList;
import java.util.List;

public class KlgMoreActivity extends BaseKlgActivity {

    public static final int RESULT_CANCEL = 0x66; //点击“荐”
    public static final int RESULT_TRAIN=0x67;//有过训练
    public static final int RESULT_EXIT = 0x77;  //退出训练


    private int mCurrentPosition=-1;
    private MoreMenuAdapter mAdapter;
    private Fragment mCurrentFragment;
    private KlgCommonBean mKlgCommonBean;
    private WordArticulation wordArticulation;
//    private List<MoreSlideMenuModel> trainRecordList;
    private List<ExpressPracticeModel> expressPracticeModelList;
    private List<MoreSlideMenuModel> trainRecordList,originalTrainRecordList;
    private int resultCode=RESULT_EXIT;
    private boolean haiTrain;


    private OnItemClickListener mOnItemClickListener = new OnItemClickListener() {
        @Override
        public void onItemClick(int position) {
            if (mCurrentPosition == position)
                return;
            trainRecordList.get(mCurrentPosition<0?0:mCurrentPosition).setSelected(0);
            trainRecordList.get(position).setSelected(1);
            mCurrentPosition = position;
            mAdapter.notifyDataSetChanged();
            changeFragment();
        }
    };

    private View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(System.currentTimeMillis()-time<500){
                return;
            }
            time=System.currentTimeMillis();
//            Log.e("John","onEnterClick:"+mModel.getMoreModuleDetails().get(mCurrentPosition).getModuleName());
            Log.e("aaaa","onEnterClick:"+mCurrentPosition);
//            KlgBasicTrainActivity.launch(this,);
            String TrainTag=trainRecordList.get(mCurrentPosition).getModuleTag();
            MoreSlideMenuModel model = trainRecordList.get(mCurrentPosition);
            KlgBasicTrainActivity.launch(KlgMoreActivity.this,mKlgCommonBean,wordArticulation,expressPracticeModelList,model,TrainTag);
        }
    };



    /**
     */
    public static void launch(Context context, int requestCode, KlgCommonBean commonBean, WordArticulation wordArticulation,
                              List<ExpressPracticeModel> expressPracticeModelList,List<MoreSlideMenuModel> trainRecordList){
        Intent intent = new Intent(context, KlgMoreActivity.class);
        intent.putExtra("extra_common_bean",commonBean);
        intent.putExtra("extra_word_articulation",wordArticulation);
        intent.putParcelableArrayListExtra("extra_practice_list",(ArrayList)expressPracticeModelList);
        intent.putParcelableArrayListExtra("extra_train_record",(ArrayList)trainRecordList);
        ((Activity)context).startActivityForResult(intent,requestCode);
    }

    @Override
    protected void setViewAndUpdata() {

        RecyclerView recyclerView = findViewById(R.id.recycler_view);
        findViewById(R.id.tv_enter).setOnClickListener(mOnClickListener);
        Intent intent = getIntent();
        originalTrainRecordList = intent.getParcelableArrayListExtra("extra_train_record");
//        List<MoreSlideMenuModel> passTrainRecordList=new ArrayList<>();
//        List<MoreSlideMenuModel> unPassTrainRecordList=new ArrayList<>();
        trainRecordList = new ArrayList<>();
//        for (MoreSlideMenuModel model: originalTrainRecordList){
//            if(model.getIsPass()==1){
//                passTrainRecordList.add(model);
//            }else{
//                unPassTrainRecordList.add(model);
//            }
//        }
//        trainRecordList.addAll(passTrainRecordList);
        trainRecordList.addAll(originalTrainRecordList);
        mKlgCommonBean=(KlgCommonBean)intent.getSerializableExtra("extra_common_bean");
        wordArticulation=(WordArticulation)intent.getSerializableExtra("extra_word_articulation");
        expressPracticeModelList = intent.getParcelableArrayListExtra("extra_practice_list");
        KLog.json(JSON.toJSONString(trainRecordList));
        mCurrentFragment = getSupportFragmentManager().findFragmentById(R.id.framelayout);
        mAdapter = new MoreMenuAdapter(trainRecordList,mOnItemClickListener);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(mAdapter);
        for(int i=0;i<trainRecordList.size();i++){
            if (trainRecordList.get(i).getIsPass()==0
                    ||i==trainRecordList.size()-1){
                mOnItemClickListener.onItemClick(i);
                break;
            }
        }
        invalidateOptionsMenu();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.klg_menu_basic_train,menu);
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        menu.findItem(R.id.menu_train).getActionView().findViewById(R.id.img_train_pause).setVisibility(View.GONE);
        menu.findItem(R.id.menu_train).getActionView().findViewById(R.id.img_operate).setVisibility(View.GONE);

        menu.findItem(R.id.menu_train).getActionView().findViewById(R.id.img_card).setOnClickListener(this);
        menu.findItem(R.id.menu_train).getActionView().findViewById(R.id.klg_icon_model_change).setOnClickListener(this);
        ( (ImageView) (menu.findItem(R.id.menu_train).getActionView().findViewById(R.id.klg_icon_model_change) ) )
                .setImageResource(R.mipmap.klg_icon_model_more);
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v.getId() == R.id.img_card
                && mKlgCommonBean !=null){
            KlgCardDialogManager.getInstance().showKnowledgeCardDialog(this,mKlgCommonBean,true,false,null);

        }else if (v.getId() == R.id.klg_icon_model_change){
            onBackPressed();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId()==android.R.id.home){
            setResult(RESULT_EXIT);
        }
        return super.onOptionsItemSelected(item);
    }


    private void changeFragment(){
        String trainModule = trainRecordList.get(mCurrentPosition).getModuleTag();

        if (mCurrentFragment != null){
            getSupportFragmentManager()
                    .beginTransaction()
                    .hide(mCurrentFragment)
                    .commit();
        }
        mCurrentFragment = getSupportFragmentManager()
                .findFragmentByTag(trainModule);

        if (mCurrentFragment != null){
            getSupportFragmentManager()
                    .beginTransaction()
                    .show(mCurrentFragment)
                    .commit();

        }else {
            Bundle mBundle=new Bundle();
            mBundle.putSerializable(BasicTrainBaseFragment.KEY_SPELL_ARTICULATION,wordArticulation);
            mBundle.putSerializable(KlgBasicTrainActivity.KEY_KLGCOMMONBEN,mKlgCommonBean);
            mBundle.putParcelableArrayList(BasicTrainBaseFragment.KEY_USAGE_TRAIN,(ArrayList) expressPracticeModelList);
            mBundle.putBoolean(BasicTrainBaseFragment.KEY_ENABLE_TRAIN,false);
            mBundle.putBoolean(BasicTrainBaseFragment.KEY_IS_ALERT,true);
            switch (trainModule){
                case BasicTrainBaseFragment.TRAINTAG_SPELL://单词拼读
                    mCurrentFragment=new SpellTrainFragment();
                    mCurrentFragment.setArguments(mBundle);
                    break;
                case BasicTrainBaseFragment.TRAINTAG_SPELL_FILL://填空拼写
                    mCurrentFragment=new FillSpellTrainFragment();
                    mCurrentFragment.setArguments(mBundle);
                    break;
                case BasicTrainBaseFragment.TRAINTAG_SPELL_MEMORY_WRITE://全拼默写
                    mCurrentFragment=new SpellMemoryWriteFragment();
                    mCurrentFragment.setArguments(mBundle);
                    break;
                case BasicTrainBaseFragment.TRAINTAG_PHONETIC://发音训练
                    mCurrentFragment=new PronunciatioTrainFragment();
                    mCurrentFragment.setArguments(mBundle);
                    break;
                case BasicTrainBaseFragment.TRAINTAG_PHONETIC_PHRASE://词组，esp发音训练
                    mCurrentFragment=new PronunciatioPhraseTrainFragment();
                    mCurrentFragment.setArguments(mBundle);
                    break;
                case BasicTrainBaseFragment.TRAINTAG_USAGE://用法训练，读句填空
                    mCurrentFragment=new UsageTrainFragment();
                    mCurrentFragment.setArguments(mBundle);
                    break;
                case BasicTrainBaseFragment.TRAINTAG_LISTEN_REPEAT://听音复述
                    mCurrentFragment = MoreRepeatFragment.newInstance();
                    break;
                case BasicTrainBaseFragment.TRAINTAG_TRANSLATION://口语翻译
                    mCurrentFragment = MoreTranslationFragment.newInstance(expressPracticeModelList.get(0).getOneSentenceList().get(0).getTranslate());
                    break;
            }

            if (mCurrentFragment != null){
                getSupportFragmentManager()
                        .beginTransaction()
                        .add(R.id.framelayout,mCurrentFragment,trainModule)
                        .commit();
            }
        }
    }

    @Override
    protected int getContentViewId() {
        return R.layout.klg_activity_more;
    }

    @Override
    protected String getTitleName() {
        return "";
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e("aaaa","requestCode:"+requestCode+"....+resultCode:"+resultCode);
        if(resultCode==201&&requestCode==105){
            Log.e("aaaa","全->荐");
            haiTrain=true;
            if(originalTrainRecordList==null){
                return;
            }
            MoreSlideMenuModel moreSlideMenuModel=data.getParcelableExtra("trainRecord");
            if(moreSlideMenuModel!=null){
                KLog.json(JSON.toJSONString(moreSlideMenuModel));
                for (MoreSlideMenuModel model:originalTrainRecordList){
                    if(TextUtils.equals(model.getModuleTag(),moreSlideMenuModel.getModuleTag())){
                        model.setIsPass(moreSlideMenuModel.getIsPass());
                        break;
                    }
                }
            }
            onBackPressed();
        }else if(resultCode==101&&requestCode==105){
            haiTrain=true;
            if(data==null){
                return;
            }
            if(originalTrainRecordList==null){
                return;
            }
            String currentModuleTag = trainRecordList.get(mCurrentPosition).getModuleTag();
            MoreSlideMenuModel moreSlideMenuModel=data.getParcelableExtra("trainRecord");
            if(moreSlideMenuModel!=null){
                KLog.json(JSON.toJSONString(moreSlideMenuModel));
                for (MoreSlideMenuModel model:originalTrainRecordList){
                    if(TextUtils.equals(model.getModuleTag(),moreSlideMenuModel.getModuleTag())){
                        model.setIsPass(moreSlideMenuModel.getIsPass());
                        break;
                    }
                }
//                //更新侧边栏的过关样式
//              List.addAll(unPassTrainRecordList);

                for (int i =0;i<trainRecordList.size();i++){
                    MoreSlideMenuModel menuModel = trainRecordList.get(i);
                    if (menuModel.getModuleTag().equals(currentModuleTag)){
                        mCurrentPosition = i;
                        break;
                    }
                }

                for(int i=0;i<trainRecordList.size();i++){
                    if (trainRecordList.get(i).getIsPass()==0
                            ||i==trainRecordList.size()-1){
                        mOnItemClickListener.onItemClick(i);
                        break;
                    }
                }
//                mAdapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    public void onBackPressed() {
        Intent mIntent=new Intent();
        if(originalTrainRecordList!=null){
            mIntent.putParcelableArrayListExtra("originalTrainRecordList",(ArrayList)originalTrainRecordList);
        }
        setResult(haiTrain?RESULT_TRAIN:RESULT_CANCEL,mIntent);
        super.onBackPressed();
    }
}
